package com.mflex.WHSmartWhouseAd.activity;

import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import com.mflex.WHSmartWhouseAd.R;
import com.mflex.WHSmartWhouseAd.adapter.ShipmentBoxNoAdapter;
import com.mflex.WHSmartWhouseAd.model.CommitShipSubmitModel;
import com.mflex.WHSmartWhouseAd.model.CommonRequest;
import com.mflex.WHSmartWhouseAd.model.ShipmentBoxNoPdaInfo;
import com.mflex.WHSmartWhouseAd.utils.XToastUtils;
import com.xuexiang.xhttp2.XHttp;
import com.xuexiang.xhttp2.callback.SimpleCallBack;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xui.utils.WidgetUtils;
import com.xuexiang.xui.widget.dialog.MiniLoadingDialog;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.xuexiang.xutil.common.StringUtils;
import com.xuexiang.xutil.net.JsonUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class SecondaryConfirmOfShipmentActivity extends BaseActivity implements AdapterView.OnItemClickListener  {

    // 出库编号
    EditText stvShipmentNumber;
    // 料号
    EditText stvMaterial;
    // 箱号
    EditText stvBoxNo;
    // 需求数量
    EditText stvQuantityRequired;
    // 扫描数量
    EditText stvActualScanNumber;
    // 列表
    ListView lvList;
    // 清空
    Button buttonClear;
    // 提交
    Button buttonSubmit;

    // loading
    MiniLoadingDialog miniLoadingDialog;
    List<ShipmentBoxNoPdaInfo>ShipmentBoxNoModelList=new ArrayList<>();
    CommitShipSubmitModel model = new CommitShipSubmitModel();
    private double ActualScanNumber=0;//扫描数量
    private String ActualQuantityRequired;//总数量
    private String userName;
    private String BPMno;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_secondary_confirm_shipment);
        // 弹窗提示
        miniLoadingDialog =WidgetUtils.getMiniLoadingDialog(this,"加载...");
//        id绑定
        stvShipmentNumber = findViewById(R.id.stv_ShipmentNumber);
        stvMaterial = findViewById(R.id.stv_Material);
        stvBoxNo = findViewById(R.id.stv_BoxNo);
        stvQuantityRequired = findViewById(R.id.stv_QuantityRequired);
        stvActualScanNumber = findViewById(R.id.stv_ActualScanNumber);
        lvList = findViewById(R.id.lvList);
        buttonClear = findViewById(R.id.button_clear);
        buttonSubmit = findViewById(R.id.button_submit);

        // 传递数据
        Intent intent = getIntent();
        userName = intent.getStringExtra("userName");
        BPMno = intent.getStringExtra("BPMno");
        stvShipmentNumber.setText(intent.getStringExtra("ShipNo"));
        ActualQuantityRequired = intent.getStringExtra("CountQty");
        stvMaterial.setText(intent.getStringExtra("MaterialNo"));
        // 视图按键监听器
        stvBoxNo.setOnKeyListener(this);
        buttonSubmit.setOnClickListener(this);
        buttonClear.setOnClickListener(this);
        stvActualScanNumber.setText(String.valueOf(ActualScanNumber));//扫描数量
        stvQuantityRequired.setText(String.valueOf(ActualQuantityRequired));//需求数量
        stvBoxNo.requestFocus();
    }
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.button_clear:
                ShipmentBoxNoModelList.clear();
                ShipmentBoxNoAdapter ShipmentBoxNoAdapter = new ShipmentBoxNoAdapter(SecondaryConfirmOfShipmentActivity.this,ShipmentBoxNoModelList);
                lvList.setAdapter(ShipmentBoxNoAdapter);
                stvBoxNo.setText("");
                ActualScanNumber = 0;
                stvActualScanNumber.setText(String.valueOf(ActualScanNumber));
                break;
            case R.id.button_submit:
                saveButtonMd(view);
                break;
            default:
                break;
        }

    }
    @Override
    public boolean onKey(View view, int i, KeyEvent keyEvent) {
        if (keyEvent.getAction() == KeyEvent.ACTION_DOWN && (i == 66 || i == 61)) {
            switch (view.getId()) {
                case R.id.stv_BoxNo: // 包号/盘号
                    chekBoxNo();
                    break;
                default:
                    break;
            }
        }
        return false;
    }

    //    箱号回车事件触发接口
    private void chekBoxNo() {

        if(StringUtils.isEmpty(stvBoxNo.getText().toString())) {
            return;
        }
        // 累加数量不能大于需求数量
        int num=(int)Math.round(Double.parseDouble(ActualQuantityRequired));
        if(ActualScanNumber > num) {
            MediaPlayer mp = MediaPlayer.create(SecondaryConfirmOfShipmentActivity.this,R.raw.error_voice);mp.start();
            new MaterialDialog.Builder(SecondaryConfirmOfShipmentActivity.this)
                    .iconRes(R.drawable.icon_warning)
                    .title(R.string.tip_warning)
                    .content("超出需求数量！")
                    .positiveText(R.string.lab_submit)
                    .show();
            return;
        }

        //      测试
//        ShipmentBoxNoPdaInfo items = new ShipmentBoxNoPdaInfo();
//        double adm =   Math.random();
//        items.setBoxName("123");
//        items.setBoxQty(String.valueOf(20));
//        items.setMaterialNo("料号");
//        items.setBoxID("id1");
//
//        ActualScanNumber +=Double.parseDouble(items.getBoxQty());
//        stvActualScanNumber.setText(String.valueOf(ActualScanNumber));
//        ShipmentBoxNoModelList.add(items);
//        ShipmentBoxNoAdapter ShipmentBoxNoAdapter = new ShipmentBoxNoAdapter(SecondaryConfirmOfShipmentActivity.this,ShipmentBoxNoModelList);
//
//        lvList.setAdapter(ShipmentBoxNoAdapter);
        //      结束

        boolean ischeck = true;
        // 重复扫描卡控
        if(!ShipmentBoxNoModelList.isEmpty()) {
            for(ShipmentBoxNoPdaInfo item: ShipmentBoxNoModelList) {
                if(Objects.equals(item.getBoxName(), stvBoxNo.getText().toString())) {
                    ischeck = false;
                    break;
                }
            }
        }
        if(!ischeck) {
            MediaPlayer mp = MediaPlayer.create(SecondaryConfirmOfShipmentActivity.this,R.raw.error_voice);mp.start();
            new MaterialDialog.Builder(SecondaryConfirmOfShipmentActivity.this)
                    .iconRes(R.drawable.icon_warning)
                    .title(R.string.tip_warning)
                    .content("箱号"+stvBoxNo.getText().toString()+"在列表中已存在")
                    .positiveText(R.string.lab_submit)
                    .show();
            stvBoxNo.setText("");
            stvBoxNo.requestFocus();
            return;

        }
        miniLoadingDialog.show();
        XHttp.get("api/WHSmartWhousePDA/ShipRowSetBox")
                .params("BoxName",stvBoxNo.getText().toString())
                .params("MaterialName",stvMaterial.getText().toString())
                .params("CountQty",stvQuantityRequired.getText().toString())
                .syncRequest(false)
                .onMainThread(true)
                .execute(new SimpleCallBack<ShipmentBoxNoPdaInfo>() {
                    @Override
                    public  void  onSuccess(ShipmentBoxNoPdaInfo response) {
                        miniLoadingDialog.dismiss();

                        ActualScanNumber +=Double.parseDouble(response.getBoxQty());
                        ShipmentBoxNoModelList.add(response);
                        ShipmentBoxNoAdapter ShipmentBoxNoAdapter = new ShipmentBoxNoAdapter(SecondaryConfirmOfShipmentActivity.this,ShipmentBoxNoModelList);

                        lvList.setAdapter(ShipmentBoxNoAdapter);

                        stvActualScanNumber.setText(String.valueOf(ActualScanNumber));
                        stvBoxNo.setText("");
                        stvBoxNo.requestFocus();
                    }
                    @Override
                    public void onError(ApiException e) {
                        miniLoadingDialog.dismiss();
                        stvBoxNo.setText("");
                        stvBoxNo.requestFocus();
                        MediaPlayer mp = MediaPlayer.create(SecondaryConfirmOfShipmentActivity.this,R.raw.error_voice);mp.start();
                        new MaterialDialog.Builder(SecondaryConfirmOfShipmentActivity.this)
                                .iconRes(R.drawable.icon_warning)
                                .title(R.string.tip_warning)
                                .content(e.getMessage())
                                .positiveText(R.string.lab_submit)
                                .show();
                    }
                });

    }
    private void saveButtonMd(View v) {
        int num=(int)Math.round(Double.parseDouble(ActualQuantityRequired));
        if(ActualScanNumber != num) {
            MediaPlayer mp = MediaPlayer.create(SecondaryConfirmOfShipmentActivity.this,R.raw.error_voice);mp.start();
            new MaterialDialog.Builder(SecondaryConfirmOfShipmentActivity.this)
                    .iconRes(R.drawable.icon_warning)
                    .title(R.string.tip_warning)
                    .content("提交失败,大于或小于需求数量！")
                    .positiveText(R.string.lab_submit)
                    .show();
            return;
        }
        List<String> BoxIds =new ArrayList<>();
        for (ShipmentBoxNoPdaInfo item:
             ShipmentBoxNoModelList) {
            BoxIds.add(item.getBoxID());
        }
        model.setInUser(userName);
        model.setBpmNo(BPMno);
        model.setShipNo(stvShipmentNumber.getText().toString());
        model.setJDEPN(stvMaterial.getText().toString());
        model.setShipQty(String.valueOf(ActualQuantityRequired));
        model.setBoxIds(BoxIds);

//        CommonRequest request =new CommonRequest();
//        request.setJson(JsonUtil.toJson(model));
        String json = JsonUtil.toJson(model);
        Log.d("1234",json);
        miniLoadingDialog.show();
        XHttp.post("api/WHSmartWhousePDA/ShipSubmit")
                .upJson(JsonUtil.toJson(model))
                .syncRequest(false)
                .onMainThread(true)
                .accessToken(true)
                .timeOut(150000)
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onSuccess(String response) {
                        miniLoadingDialog.dismiss();
                        XToastUtils.success("提交成功",3000);
                        ShipmentBoxNoModelList.clear();
                        ShipmentBoxNoAdapter ShipmentBoxNoAdapter = new ShipmentBoxNoAdapter(SecondaryConfirmOfShipmentActivity.this,ShipmentBoxNoModelList);
                        lvList.setAdapter(ShipmentBoxNoAdapter);
                        ActualScanNumber = 0;
                        stvActualScanNumber.setText(String.valueOf(ActualScanNumber));
                        stvBoxNo.setText("");
                        stvBoxNo.requestFocus();
                    }
                    @Override
                    public void onError(ApiException e) {
                        miniLoadingDialog.dismiss();
                        MediaPlayer mp =MediaPlayer.create(SecondaryConfirmOfShipmentActivity.this,R.raw.error_voice);mp.start();
                        new MaterialDialog.Builder(SecondaryConfirmOfShipmentActivity.this)
                                .iconRes(R.drawable.icon_warning)
                                .title(R.string.tip_warning)
                                .content(e.getMessage())
                                .positiveText(R.string.lab_submit)
                                .show();
                    }

                });
    }




    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    }
}